package Offer.offer2019;

/**
 * 替换空格
 * @author: leiwenkang02@meituan.com
 * @date: 2019/4/16
 * @time: 20:33
 */
public class Offer04 {

    public static void main(String[] args) {
        Offer04 offer04 = new Offer04();
        char[] ch = offer04.replaceBlank("We are happy".toCharArray());
        System.out.println(ch);
    }

    public char[] replaceBlank(char[] ch) {
        if (ch == null || ch.length == 0) {
            return ch;
        }

        //1.先得到原字符数组中的空格数
        int blankCount = 0;
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] == ' ') {
                blankCount++;
            }
        }

        //2.计算新字符数组的长度   newLength = oldLength + 2 * blankCount
        int newLength = ch.length + 2 * blankCount;
        char[] newCh = new char[newLength];

        //3.填充新的字符数组
        int i = 0;
        int j = 0;
        while (i < ch.length) {
            if (ch[i] != ' '){
                newCh[j++] = ch[i++];//若不是空格，则新字符数组与原字符数组赋值相等
            } else {
                newCh[j++] = '%';//若是空格，按规则填充空格
                newCh[j++] = '2';
                newCh[j++] = '0';
                i++;
            }
        }

        return newCh;
    }
}
